<template>
  <div class="xr-table-header">
    <template v-if="showSceneAndFilter">
      <flexbox
        class="xr-table-header__body"
        align="center">
        <template v-if="showSceneView">
          <div class="scene">
            场景：
          </div>
          <el-popover
            v-model="showScene"
            trigger="click"
            popper-class="no-padding-popover"
            width="180">
            <el-input
              slot="reference"
              v-model="sceneName"
              :readonly="true"
              placeholder="请选择"
              class="scene-select">
              <i
                slot="suffix"
                :class="['el-input__icon', 'el-icon-' + iconClass]" />
            </el-input>
            <scene-list
              :type="type"
              @scene="sceneSelect"
              @command="handleSceneCommand"
              @hidden-scene="showScene=false" />
          </el-popover>
        </template>

        <el-button
          icon="wk wk-screening"
          type="primary"
          style="margin-left: 20px"
          @click="getFilterFieldInfo">
          高级筛选
        </el-button>
      </flexbox>
    </template>

    <template v-else>
      <flexbox
        class="xr-table-header__handle">
        <div class="selected—title">已选中 <span class="selected—count">{{ selects.length }}</span> 项</div>
        <flexbox-item
          v-if="selects.length > 0"
          class="selection-items-box">
          <el-button
            v-for="(item, index) in handles"
            :icon="item.icon | wkIconPre"
            :key="index"
            type="primary"
            @click.native="selectionBarClick(item.command)">
            {{ item.label }}
          </el-button>
        </flexbox-item>
      </flexbox>
    </template>

    <filter-content
      v-if="advancedFilterList.length > 0"
      :list="advancedFilterList"
      @delete="handleDeleteField" />

    <slot name="append" />

    <wk-advanced-filter
      v-if="showFilter"
      v-model="advancedFilterList"
      :field-list="fieldList"
      @confirm="handleFilter"
      @close="showFilter = !showFilter" />

    <scene-create
      v-if="showSceneCreate"
      :type="type"
      @update="handleUpdateScene"
      @close="showSceneCreate = !showSceneCreate" />

    <scene-set
      v-if="showSceneSet"
      :type="type"
      @update="handleUpdateScene"
      @close="showSceneSet = !showSceneSet" />
  </div>
</template>

<script>
import { jxcFieldSceneQueryFieldAPI } from '@/api/jxc/field'
import { jxcSceneAddAPI } from '@/api/jxc/scene'

import SceneList from './SceneForm/SceneList'
import SceneCreate from './SceneForm/SceneCreate'
import SceneSet from './SceneForm/SceneSet'

import WkAdvancedFilter from './WkAdvancedFilter'
import FilterContent from './WkAdvancedFilter/FilterContent'

import jxcTypes from '../jxcTypes'
import jxcExamineLib from '../jxcExamineStatus'
import { isArray } from '@/utils/types'

export default {
  // 表头
  name: 'XrTableHeader',
  components: {
    SceneList,
    SceneCreate,
    SceneSet,
    FilterContent,
    WkAdvancedFilter
  },
  props: {
    selects: {
      type: Array,
      default: () => {
        return []
      }
    },
    handles: {
      type: Array,
      default: () => {
        return []
      }
    },
    type: {
      type: String,
      default: ''
    },
    hideFilter: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      showSceneView: true,
      showScene: false, // 场景操作
      sceneData: { id: '', bydata: '', name: '' },
      sceneType: null,

      showSceneSet: false, // 场景设置控制标志
      showSceneCreate: false, // 场景添加控制标志

      fieldList: [], // 高级筛选字段列表
      showFilter: false, // 高级筛选控制标志
      advancedFilterList: [] // 高级筛选已经选择的条件
    }
  },
  computed: {
    typeObj() {
      return jxcTypes[this.type]
    },
    iconClass() {
      return this.showScene ? 'arrow-up' : 'arrow-down'
    },
    sceneName() {
      const map = {
        jxc_product: '全部产品',
        jxc_supplier: '全部供应商',
        jxc_purchase: '全部采购订单',
        jxc_retreat: '全部采购退货',
        jxc_sale: '全部销售订单',
        jxc_salereturn: '全部销售退货',
        jxc_receipt: '全部入库',
        jxc_collection: '全部回款',
        jxc_payment: '全部付款'
      }
      return this.sceneData.name || map[this.type] || ''
    },
    showSceneAndFilter() {
      return !this.hideFilter &&
        (!this.selects ||
          this.selects.length === 0 ||
          this.handles.length === 0)
    }
  },
  watch: {
    typeObj: {
      handler(val) {
        console.log('val', val)
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    /**
     * 选中后的按钮操作
     * @param command
     */
    selectionBarClick(command) {
      this.$emit('command', command)
    },

    /**
     * 切换场景
     */
    sceneSelect(data) {
      this.sceneData = data
      this.$emit('scene', data)
    },

    /**
     * 场景操作
     */
    handleSceneCommand(command) {
      if (command === 'add') {
        this.showSceneCreate = !this.showSceneCreate
      } else if (command === 'set') {
        this.showSceneSet = !this.showSceneSet
      }
    },

    /**
     * 更新场景
     */
    handleUpdateScene() {
      this.showSceneView = false
      this.$nextTick(() => {
        this.showSceneView = true
      })
    },

    /**
     * 查询高级筛选字段
     */
    getFilterFieldInfo() {
      jxcFieldSceneQueryFieldAPI({
        label: this.typeObj.label
      }).then(res => {
        console.log('fieldList', res)

        res.data.forEach(item => {
          if (item.fieldName === 'product_ishelf') {
            item.setting = [
              { label: '上架', value: 1 },
              { label: '下架', value: 0 }
            ]
          } else if (item.formType === 'state_cause') {
            item.setting = []
            jxcExamineLib.forEach(o => {
              if (this.type === 'jxc_receipt') {
                if ([5, 6].includes(o.jxc_state)) {
                  item.setting.push({
                    label: o.label,
                    value: o.jxc_state
                  })
                }
              } else if (this.type === 'jxc_outbound') {
                if ([4, 6].includes(o.jxc_state)) {
                  item.setting.push({
                    label: o.label,
                    value: o.jxc_state
                  })
                }
              } else if (![0, 1, 4, 5].includes(o.jxc_state)) {
                item.setting.push({
                  label: o.label,
                  value: o.jxc_state
                })
              }
            })
          }
        })

        this.fieldList = res.data
        this.showFilter = true
      }).catch(() => {})
    },

    /**
     * 筛选
     */
    handleFilter(filterData) {
      console.log('filter form: ', filterData)

      this.showFilter = false
      const arr = []
      this.advancedFilterList = filterData.list
      this.advancedFilterList.forEach(item => {
        arr.push({
          formType: item.formType,
          name: item.fieldName,
          type: item.conditionVal,
          values: this.getFilterValue(item.value, item.formType)
        })
      })

      // 保存为场景
      if (filterData.scene) {
        jxcSceneAddAPI({
          searchList: arr,
          type: this.typeObj.label,
          ...filterData.scene
        }).then(() => {
          this.handleUpdateScene()
        }).catch(() => {})
      }

      this.$emit('filter', arr)
    },

    /**
     * 根据条件取对应的type值
     * @param condition
     * @param formType
     * @returns {*|number}
     */
    getFilterCondition(condition, formType) {
      if (['date', 'datetime'].includes(formType)) {
        condition = formType
      }
      return {
        is: 1, // 等于
        isNot: 2, // 不等于
        contains: 3, // 包含
        notContains: 4, // 不包含
        isNull: 5, // 为空
        isNotNull: 6, // 不为空
        gt: 7, // 大于
        egt: 8, // 大于等于
        lt: 9, // 小于
        elt: 10, // 小于等于
        date: 13, // 日期
        datetime: 12 // 日期时间
      }[condition] || 3
    },

    /**
     * 获取条件对应的值
     * @param val
     * @param formType
     * @returns {*[]|*}
     */
    getFilterValue(val, formType) {
      if (!val) return []
      return isArray(val) ? val : [val]
    },

    /**
     * 删除某个筛选条件
     * @param index
     */
    handleDeleteField(index) {
      this.advancedFilterList.splice(index, 1)
      const arr = []
      this.advancedFilterList.forEach(item => {
        arr.push({
          formType: item.formType,
          name: item.fieldName,
          type: this.getFilterCondition(item.condition, item.formType),
          values: this.getFilterValue(item.value, item.formType)
        })
      })
      this.$emit('filter', arr)
    }
  }
}
</script>

<style lang="scss" scoped>
.xr-table-header {
  background: white;

  &__body {
    font-size: 13px;
    height: 50px;
    padding: 0 20px;

    .scene-select {
      /deep/ .el-input__inner {
        cursor: pointer;
      }
    }
  }

  &__handle {
    font-size: 12px;
    height: 50px;
    padding: 0 20px;
    color: #777;

    .selected—title {
      width: auto;
      flex-shrink: 0;
      padding-right: 20px;
      color: #333;
      .selected—count {
        color: $xr-color-primary;
      }
    }

    .selection-items-box {
      overflow-x: auto;
      overflow-y: hidden;
      padding: 0 15px;

      .el-button {
        color: #666;
        background-color: $xr--background-color-base;
        border-color: $xr--background-color-base;
        font-size: 12px;
        height: 28px;
        border-radius: 14px;
        /deep/ i {
          font-size: 12px;
          margin-right: 5px;
        }
      }

      .el-button--primary:hover {
        background: $xr-color-primary;
        border-color: $xr-color-primary;
        color: #ffffff;
      }

      .el-button + .el-button {
        margin-left: 15px;
      }
    }
  }
}
</style>
